package nginx_logic

import (
	"context"
	"strings"
	"time"
	"yunzhan/common/utils"
	agent "yunzhan/rpc-server/pb"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryNginxConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryNginxConfigLogic 获取Nginx配置
func NewQueryNginxConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryNginxConfigLogic {
	return &QueryNginxConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryNginxConfigLogic) QueryNginxConfig(req *types.QueryConfigRequest) (resp *types.BaseConfigResponse, err error) {
	if req.ClusterID == "" || req.NodeHost == "" {
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Invalid request parameters",
		}, nil
	}

	agentPort := strings.Split(l.svcCtx.Config.RpcService.ListenOn, ":")[1]

	conn, err := utils.SafeNewClient(req.NodeHost, agentPort)
	if err != nil {
		logx.Errorf("Failed to create RPC connection: %v", err)
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Failed to create RPC connection",
		}, err
	}

	client := agent.NewNginxDeployClient(conn.Conn())

	ctx, cancel := context.WithTimeout(l.ctx, 10*time.Second)
	defer cancel()

	nginxConfig, err := client.GetNginxConfig(ctx, &agent.GetNginxConfRequest{
		NodeHost:  req.NodeHost,
		ClusterID: req.ClusterID,
	})
	if err != nil {
		logx.Errorf("Failed to query Nginx config: %v", err)
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Failed to query configuration",
		}, err
	}

	if nginxConfig == nil {
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Received nil response from server",
		}, nil
	}

	return &types.BaseConfigResponse{
		Code:    nginxConfig.Code,
		Message: nginxConfig.Message,
		Data:    nginxConfig.Content,
	}, nil
}
